/* eslint-disable consistent-return */

// 每次做更新和删除都校验每条record是否符合检验规则
const valiadatorRecords = (dataSet) => {
  // 只检验record的某个单独的字段
  dataSet.forEach((eachRecord) => eachRecord.getField('key').checkValidity());
};
// 监听数据更新
const handleUpdate = ({
  dataSet, record, name, value, oldValue,
}) => {
  if (name === 'key') {
    valiadatorRecords(dataSet);
  }
};
// 监听数据移除
const handleRemove = ({ dataSet }) => {
  valiadatorRecords(dataSet);
};
export default ({ formatMessage }) => {
  // 校验key字段
  function checkKey(value, name, record) {
    const pa = /^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/)?([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$/;
    if (value) {
    // 判断输入的字符串是否符合校验规则
      if (!pa.test(value)) {
        return formatMessage({ id: 'domain.annotation.check.failed' });
      }
      // 判断键是否有重复
      const ds = record.dataSet;
      const hasRepeat = ds.some((annotationrecord) => annotationrecord.id !== record.id
        && value === annotationrecord.get('key'));
      if (hasRepeat) {
        return formatMessage({ id: 'domain.annotation.check.repeat' });
      }
    }
  }
  // 校验值字段
  function checkValue(value, name, record) {
    // 键和值必须同时存在
    if (!value && record.get('key')) {
      return formatMessage({ id: 'mapping.keyValueSpan' });
    }
  }
  return ({
    autoQuery: false,
    autoCreate: false,
    paging: false,
    pageSize: 10,
    queryFields: [

    ],
    fields: [
      {
        name: 'key',
        type: 'string',
        validator: checkKey,
        maxLength: 316,
        label: formatMessage({ id: 'key' }),
      },
      {
        name: 'value',
        type: 'string',
        validator: checkValue,
        label: formatMessage({ id: 'value' }),
      },
    ],
    transport: {

    },
    events: {
      update: handleUpdate,
      remove: handleRemove,
    },
  });
};
